// 用户管理

package user

import (
	dbModel "ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/cfg"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"ZHONGYIHANGYAN/mysql"
	"fmt"
	"time"
)

type UserManage struct {
	mysql.DataBase
}

var defaultUserManage = &UserManage{}

func Manage() *UserManage {
	return defaultUserManage
}

// 初始化通道相关的表
func InitTable(DB *mysql.MysqlGorm) {
	defaultUserManage.DataBase = DB

	/* 自动创建表结构 */
	defaultUserManage.autoMigrate()

	// 创建默认用户
	defaultUserManage.CreateDefaultUser()
}

// 自动创建表结构
func (m *UserManage) autoMigrate() {
	m.DataBase.AutoMigrate(&dbModel.User{})
}

// 创建默认用户
func (m *UserManage) CreateDefaultUser() {
	db := m.DataBase.DB()

	// 步骤1: 删除数据库中id包含"default-user"字符的用户
	var existingUsers []dbModel.User
	db.Where("id LIKE ?", "%default-user%").Find(&existingUsers)

	for _, user := range existingUsers {
		// 删除用户
		db.Delete(&user)
	}

	// 步骤2: 根据data.json中的默认用户数据全量创建用户
	for _, userCfg := range cfg.Data.DefaultUserList {
		// 创建用户
		pwd := commUtils.MakeMD5(userCfg.Password)
		user := dbModel.User{
			Id:         userCfg.Id,
			UserCode:   userCfg.UserCode,
			UserName:   userCfg.UserName,
			Password:   pwd,
			RoleId:     userCfg.RoleId,
			DefaultUser: true,
			CreateTime: time.Now(),
			UpdateTime: time.Now(),
		}

		if err := db.Create(&user).Error; err != nil {
			fmt.Printf("创建用户失败: %v\n", err)
			continue
		}
	}
}
